package com.dianrui.moonfire.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.MyApplication;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.adapter.FeedBackAdapter;
import com.dianrui.moonfire.bean.Data;
import com.dianrui.moonfire.bean.FeedBackTypeBean;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.BitmapUtils;
import com.dianrui.moonfire.util.ConvertUtils;
import com.dianrui.moonfire.util.EventBusConstants;
import com.dianrui.moonfire.util.GlideUtil;
import com.dianrui.moonfire.util.GsonUtil;
import com.dianrui.moonfire.util.MyUtil;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.dianrui.moonfire.view.ninegride.NineView;
import com.dianrui.moonfire.view.ninegride.RatioImageView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Description:故障反馈
 * User: luoziyin
 * Date: 2020-8-17
 */
@SuppressWarnings("ALL")
public class TroubleFeedActivity extends BaseActivity implements NineView.NineViewShowCallBack {
    private List<String> imageList = new ArrayList<>();
    private String formId;
    private List<Data> feedList = new ArrayList<>();
    private List<String> idList = new ArrayList<>();
    private FeedBackAdapter feedBackAdapter;
    private boolean hasChecked = false;
    private String mvIds;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.nine)
    NineView nine;
    @BindView(R.id.input)
    EditText input;
    @BindView(R.id.grid)
    GridView feedGrid;
    @BindView(R.id.sub_feedback)
    Button subFeedback;

    @Override
    public int getContentViewId() {
        return R.layout.trouble_feed;
    }

    @Override
    public void initView() {
        customInit(true);
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                mvIds = bundle.getString("mv_id");
            }
        }
        title.setText(getString(R.string.tourble_title));
        checkLocationPerssions();
        getFeedBackType();
        imageList.add("default");
        nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);

        input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                if (text.length() > 0) {
                    subFeedback.setEnabled(true);
                    subFeedback.setBackgroundResource(R.drawable.blue_gradient);
                } else {
                    subFeedback.setEnabled(false);
                    subFeedback.setBackgroundResource(R.drawable.gray_shape);
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void initData() {
    }

    //检查是否开启定位权限,有其故意关闭权限进入APP后也要有权限提醒设置
    private void checkLocationPerssions() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
            }
        } else {
            nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);
        }

    }


    //获得反馈类型
    private void getFeedBackType() {
        XHttpRequest.getInstance().postRequests(Url.GETFEEDBACKTYPE, "", new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    FeedBackTypeBean feedBackTypeBean = GsonUtil.parseJsonToBean(response, FeedBackTypeBean.class);
                    if (feedBackTypeBean != null && !isFinishing()) {
                        feedList = feedBackTypeBean.getData();
                        if (feedList.size() > 0) {
                            if (feedBackAdapter == null) {
                                feedBackAdapter = new FeedBackAdapter(TroubleFeedActivity.this, feedList);
                                feedGrid.setAdapter(feedBackAdapter);
                            } else {
                                feedBackAdapter.notifyDataSetChanged();
                            }

                        }

                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
        feedGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LinearLayout tv = view.findViewById(R.id.choose_layout);
                TextView tv1 = view.findViewById(R.id.feed_name);
                Data data = feedList.get(position);
                formId = data.getForm_id();
                if (!idList.contains(formId)) {
                    idList.add(formId);
                    data.setChecked(true);
                    tv.setBackgroundResource(R.color.main_color);
                    tv1.setTextColor(getResources().getColor(R.color.black));
                } else {
                    data.setChecked(false);
                    idList.remove(formId);
                    tv.setBackgroundResource(R.color.white);
                    tv1.setTextColor(getResources().getColor(R.color.black));
                }
                feedBackAdapter.notifyDataSetChanged();

            }
        });
    }

    @OnClick({R.id.back, R.id.sub_feedback})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.sub_feedback:
                if (StringUtils.isEmpty(input.getText().toString().trim())) {
                    ToastUtil.showToast(getString(R.string.tourble_title1));
                } else if (idList.size()<=0) {
                    ToastUtil.showToast(getString(R.string.tourble_title2));
                } else {
                    report();
                }
                break;
            default:
                break;
        }

    }

    private void report() {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < imageList.size(); i++) {
            if (!"default".equals(imageList.get(i))) {
                jsonArray.put(ConvertUtils.bitmapToBase64(BitmapUtils.decodeSampledBitmapFromFile(imageList.get(i), 480, 480)));
            }

        }
        JSONArray jsonArray1 = new JSONArray();
        for (int i = 0; i < idList.size(); i++) {
            jsonArray1.put(idList.get(i));

        }
        showLoadingDialog(getString(R.string.upload_error));
        try {
            JSONObject jsonObject = new JSONObject();
            if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                jsonObject.put("member_id", SPUtils.getInstance().getString("member_id"));
            }
            jsonObject.put("order_id", mvIds);
            jsonObject.put("content", input.getText().toString().trim());
            jsonObject.put("photo", jsonArray);
            jsonObject.put("form_id", jsonArray1);
            XHttpRequest.getInstance().postRequests(Url.FEEDBACKS, jsonObject.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String response) {
                    if (!StringUtils.isEmpty(response)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(response);
                            if (null != jsonObject && !isFinishing()) {
                                if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    EventBus.getDefault().post(EventBusConstants.REFRESH_ORDER_DETAILS);
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                    finish();
                                } else {
                                    dismissLoadingDialog();
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                }

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void failedRequest(String result) {
                    dismissLoadingDialog();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDisplayOneImage(RatioImageView imageView, String url, int parentWidth, Context context) {
        if ("default".equals(url)) {
            addImageViewList(GlideUtil.glideLoad(false, imageView, TroubleFeedActivity.this, R.drawable.add_photo));
        } else {
            imageView.setTag(R.id.glide_tag, url);
            addImageViewList(GlideUtil.downLoader(false, imageView, TroubleFeedActivity.this));
        }
    }

    @Override
    public void onDisplayImage(RatioImageView imageView, RatioImageView closeButton, String url, int parentWidth, Context context) {
        if ("default".equals(url)) {
            addImageViewList(GlideUtil.glideLoad(false, imageView, TroubleFeedActivity.this, R.drawable.add_photo));
            if (closeButton != null) {
                closeButton.setVisibility(View.GONE);
            }
        } else {
            imageView.setTag(R.id.glide_tag, url);
            addImageViewList(GlideUtil.downLoader(false, imageView, TroubleFeedActivity.this));
            if (closeButton != null) {
                closeButton.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClickImage(int position, String url, List<String> urlList, Context context) {
        if ("default".equals(url)) {
            int count = 9;
            if (imageList.size() > 1) {
                count = 9 - imageList.size() + 1;
            }
            MyUtil.createPhotoChooseDialog(0, count, TroubleFeedActivity.this, MyApplication.getFunctionConfig(), new GalleryFinal.OnHanlderResultCallback() {
                @Override
                public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                    if (resultList == null || resultList.size() == 0) {
                        return;
                    }

                    for (int i = 0; i < imageList.size(); i++) {
                        if ("default".equals(imageList.get(i))) {
                            imageList.remove(i);
                        }
                    }
                    for (int i = 0; i < resultList.size(); i++) {
                        imageList.add(resultList.get(i).getPhotoPath());
                    }
                    if (imageList.size() < 9) {
                        imageList.add("default");
                    }
                    nine.urlList(imageList);

                }

                @Override
                public void onHanlderFailure(int requestCode, String errorMsg) {
                }
            });
        } else {
            List<String> temp = new ArrayList<>();
            int count = 0;
            for (int i = 0; i < imageList.size(); i++) {
                if (!"default".equals(imageList.get(i))) {
                    temp.add(imageList.get(i));
                } else {
                    count++;
                }
            }
            startActivity(new Intent(TroubleFeedActivity.this, BigImageActivity.class)
                    .putStringArrayListExtra("data", (ArrayList<String>) temp)
                    .putExtra("current", position));
        }
    }

    @Override
    public void onClickImageColse(int position, String url, List<String> urlList, Context context) {
        imageList.remove(position);
        int count = 0;
        for (int i = 0; i < imageList.size(); i++) {
            if ("default".equals(imageList.get(i))) {
                count++;
            }
        }
        if (count == 0) {
            imageList.add("default");
        }

        nine.urlList(imageList);
    }

    @Override
    public void onSamePhotos(List<String> mRejectUrlList) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);
                }
                break;
            default:
                break;

        }
    }


}
